﻿using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using PortDetection.Class;
using SocketService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace PortDetection
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        #region 图标

        /// <summary>
        /// 与同伴连接成功图标（看不懂就不要改！）
        /// </summary>
        private const string strConn = "";

        /// <summary>
        /// 与同伴连接异常图标（看不懂就不要改！）
        /// </summary>
        private const string strError = "";

        #endregion

        #region 检测的端口
        private const int intShikePort = 1159;

        private const int intVoidePort = 6667;

        private const int intAlarmPort = 50000;
        #endregion

        /// <summary>
        /// 与同伴连接的UDP通讯类
        /// </summary>
        SocketUDPServer socketUDPServer = new SocketUDPServer();
        /// <summary>
        /// 服务器标识和TCP通讯列表
        /// </summary>
        Dictionary<int, SocketTCPClient> dicSocketTCPClient = new Dictionary<int, SocketTCPClient>();

        /// <summary>
        /// 收到伙伴的信息时间
        /// </summary>
        DateTime ConnectDate = DateTime.Now;

        /// <summary>
        /// 服务器端口异常时间
        /// </summary>
        DateTime PortErrorDate = DateTime.Now;

        /// <summary>
        /// 是否弹出框提示
        /// </summary>
        bool isNotice = true;

        /// <summary>
        /// 是否开启服务器（指的不是本地服务器，而是两台电脑是否有服务器打开）
        /// </summary>
        bool isOpenServer = true;

        /// <summary>
        /// 是否检测端口（本地）
        /// </summary>
        bool isCheckPort = true;

        /// <summary>
        /// 服务器端口是否异常
        /// </summary>
        bool isPortError = false;


        /// <summary>
        /// 检查服务器端口线程
        /// </summary>
        Thread tcheckServerPort;

        /// <summary>
        /// 打开服务器的操作线程
        /// </summary>
        Thread tOpenServer;

        delegate void gShowInfo(string Info,long AlertId);
        gShowInfo gshowInfo;

        /// <summary>
        /// 邮件通知列表
        /// </summary>
        public static List<NoticeInfo> noticeInfos = new List<NoticeInfo>();

        /// <summary>
        /// 是否需要邮件通知
        /// </summary>
        public static bool isNoticeEmail = true;

        /// <summary>
        /// 邮件通知的操作线程
        /// </summary>
        Thread tNoticeEmail;

        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                CheckForIllegalCrossThreadCalls = false;
                WriteLog.FolderName = "PortDetectionError";
                WriteLog.LogName = "Error";

                GetNoticeInfos();

                gshowInfo = ShowInfo;
                //窗体透明
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                this.BackColor = Color.Red;
                this.TransparencyKey = this.BackColor;

                //SetWindowPos(GetForegroundWindow(), -1, 0, 0, 0, 0, 1 | 2);
                //窗口置顶
                SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 1 | 2);


                //控件按键事件
                rdmTray.Click += RdmTray_Click;
                rdmSet.Click += RdmSet_Click;
                rdmClose.Click += RdmClose_Click;
                rdmNotice.Click += RdmNotice_Click;


                //读取配置信息（服务器路径、通讯端口、远端信息）
                Profile.LoadProfile();
                if (Profile.ShikePath == "" || Profile.AlarmServrPath == "" || Profile.VideoServerPath == "" || Profile.NginxPath == "" || Profile.UDPPort == -1
                    || Profile.RemoteIP == "" || Profile.RemotePort == -1)  //如果参数不够
                {
                    this.Invoke(gshowInfo, "配置参数未完整！请补充参数！",0);

                    //弹出配置界面
                    FrmSetPath frmSetPath = new FrmSetPath();
                    if (frmSetPath.ShowDialog() == DialogResult.Yes) //如果完成配置界面
                    {
                        //正常运行
                        socketUDPServer.gSocketRecv += SocketRecv_UDP;
                        socketUDPServer.gSocketError += SocketError_UDP;
                        if (!socketUDPServer.Socket_UDP_Server(Profile.UDPPort)) //开始打通通讯端口
                        {
                            radialMenu1.Symbol = strError; //端口没打通。再见！
                            this.Invoke(gshowInfo, "本地通讯端口打开失败！请检查端口是否被占用！",0);
                            
                            return;
                        }
                        else
                        {
                            //端口打通了，开始准备给伙伴发信息
                            Thread thread = new Thread(SendConnect);
                            thread.IsBackground = true;
                            thread.Start();
                        }
                        radialMenu1.Symbol = strError;
                    }
                    else
                    {
                        //基本不可能走到这里。配置界面没有配置成功不能关闭，除非任务管理器干掉
                        radialMenu1.Symbol = strError;
                        this.Invoke(gshowInfo, "配置参数未完整！无法正常运行！",0);

                        return;
                    }

                }
                else  //如果参数完整
                {
                    //正常运行
                    socketUDPServer.gSocketRecv += SocketRecv_UDP;
                    socketUDPServer.gSocketError += SocketError_UDP;
                    if (!socketUDPServer.Socket_UDP_Server(Profile.UDPPort))
                    {
                        radialMenu1.Symbol = strError;//端口没打通。再见！
                        this.Invoke(gshowInfo, "本地通讯端口打开失败！请检查端口是否被占用！",0);


                        return;
                    }
                    else
                    {
                        radialMenu1.Symbol = strError;
                        //端口打通了，开始准备给伙伴发信息
                        Thread thread = new Thread(SendConnect);
                        thread.IsBackground = true;
                        thread.Start();
                    }
                }

                if (Profile.EmailAddress == "" || Profile.Identification == "")
                {
                    //提示一下
                    this.Invoke(gshowInfo, "邮件通知参数未完整。",1);
                    isNoticeEmail = false;
                }
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);
            }


        }

        /// <summary>
        /// 获取邮件通知信息
        /// </summary>
        private void GetNoticeInfos()
        {
            if (File.Exists(XMLFile.XMLPath)) //判断文件是否存在
            {
                noticeInfos = XMLFile.ReadXMLFile(); //存在，读取
            }
            else
            {
                XMLFile.SaveFile(noticeInfos); //不存在，保存
            }
        }

        /// <summary>
        /// 通知消息
        /// </summary>
        private void NoticeInfo(object obj)
        {
            isNoticeEmail = false;
            if (noticeInfos.Count > 0 && Profile.EmailAddress != "" && Profile.Identification != "")
            {
                string strContent = (string)obj;
                //通知
                foreach (NoticeInfo n in noticeInfos)
                {
                    SendMail Email = new SendMail(n.emailaddress, Profile.EmailAddress, "服务器异常", strContent, Profile.Identification);
                    Email.Send();
                    Thread.Sleep(1000);
                }
            }
        }

        private void RdmNotice_Click(object sender, EventArgs e)
        {
            //邮件推送配置
            FrmNotice frmNotice = new FrmNotice();
            frmNotice.ShowDialog();
        }

        private void RdmTray_Click(object sender, EventArgs e)
        {
            //最小化
            WindowState = FormWindowState.Minimized;
            return;
        }

        private void RdmClose_Click(object sender, EventArgs e)
        {
            socketUDPServer.Socket_UDP_Close(); //关闭下UDP的连接
            System.Environment.Exit(0);
        }

        private void RdmSet_Click(object sender, EventArgs e)
        {
            //服务器路径配置
            FrmSetPath frmSetPath = new FrmSetPath();
            frmSetPath.ShowDialog();
        }

        /// <summary>
        /// UDP接收信息回调
        /// </summary>
        /// <param name="IPAndPort"></param>
        /// <param name="Datas"></param>
        /// <param name="DataLength"></param>
        private void SocketRecv_UDP(string IPAndPort, byte[] Datas, int DataLength)
        {
            try
            {
                string RecvIP = IPAndPort.Split(':')[0]; //IP
                int RecvPort = Convert.ToInt32(IPAndPort.Split(':')[1]); //端口 

                if (RecvIP == Profile.RemoteIP && RecvPort == Profile.RemotePort) //如果收到的信息是由指定目标发来
                {
                    isNotice = true;  //打开提示
                    radialMenu1.Symbol = strConn; //图标更换
                    ConnectDate = DateTime.Now; //记录信息时间

                    string content = Encoding.UTF8.GetString(Datas); //转个中文看看
                    string[] contents = content.Split('&');
                    switch (contents[0])
                    {
                        case "$Server":
                            {
                                if (contents[1] == "Standby") //如果要求待机。那就待机
                                {
                                    //待机
                                    //string SendData = string.Format("$Server&Standing&{0}", DateTime.Now);
                                    //byte[] connectData = Encoding.UTF8.GetBytes(SendData);
                                    isCheckPort = Convert.ToBoolean(contents[2]) ? false : true;
                                }
                                else if (contents[1] == "OpenServer") //如果要求打开服务器。那就打开服务器
                                {
                                    isCheckPort = true;

                                    //打开各服务器并开始检查端口
                                    tOpenServer = new Thread(OpenServers);
                                    tOpenServer.IsBackground = true;
                                    tOpenServer.Start();

                                    string SendData = string.Format("$Server&OpenSuccess&{0}", DateTime.Now);
                                    byte[] connectData = Encoding.UTF8.GetBytes(SendData);
                                    socketUDPServer.Socket_UDP_Send(RecvIP, RecvPort, connectData);

                                    this.Invoke(gshowInfo, "伙伴请求本地打开各服务器！",0);
                                    WriteLog.DataLog(string.Format("伙伴({0})请求本地打开各服务器", Profile.RemoteIP));
                                }
                                else if (contents[1] == "OpenSuccess") //如果收到打开服务器成功。那就发待机
                                {
                                    //服务器成功打开
                                    isOpenServer = true;
                                    isPortError = false;  //端口正常

                                    isNoticeEmail = true;  //需要Email提示
                                    this.Invoke(gshowInfo, "伙伴服务器打开成功！",0);
                                    WriteLog.DataLog(string.Format("伙伴({0})服务器打开成功", Profile.RemoteIP));
                                }

                            }
                            break;
                    }

                }
                else if (RecvIP == "127.0.0.1" && RecvPort == Profile.UDPPort) //自己给自己发的
                {
                    string content = Encoding.UTF8.GetString(Datas); //转个中文看看
                    string[] contents = content.Split('&');
                    if (contents[0] == "$Server")
                    {
                        if (contents[1] == "OpenServer") //如果要求打开服务器。那就打开服务器
                        {
                            //打开各服务器并开始检查端口
                            tOpenServer = new Thread(OpenServers);
                            tOpenServer.IsBackground = true;
                            tOpenServer.Start();

                            string SendData = string.Format("$Server&OpenSuccess&{0}", DateTime.Now);
                            byte[] connectData = Encoding.UTF8.GetBytes(SendData);
                            socketUDPServer.Socket_UDP_Send(RecvIP, RecvPort, connectData);
                            isCheckPort = true;
                        }
                        else if (contents[1] == "OpenSuccess") //如果收到打开服务器成功。那就发待机
                        {
                            //服务器成功打开
                            isOpenServer = true;
                            isPortError = false;  //端口正常

                            isNoticeEmail = true;  //需要Email提示
                            this.Invoke(gshowInfo, "与伙伴通讯超时,本地自动打开各服务器！",0);
                            WriteLog.DataLog(string.Format("与伙伴({0})通讯超时,本地自动打开各服务器", Profile.RemoteIP));


                        }
                    }
                }
                else 
                {
                    byte[] bytsValue = GetValue(Datas, DataLength);
                    string content = Encoding.UTF8.GetString(bytsValue);
                    IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(RecvIP), RecvPort);
                    Analysis(ipPoint,content);
                }
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);

            }



        }
        #region 数据解析相关

        /// <summary>
        /// 数据解析
        /// </summary>
        /// <param name="ipPoint"></param>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public bool Analysis(IPEndPoint ipPoint, string strContent)
        {
            bool bolResult = false;
            string[] Temp_strsContent = strContent.Split('&');
            switch (Temp_strsContent[0])
            {
                case "$request":
                    Analysis_serverstatus(ipPoint,Temp_strsContent[1]);
                    break;
            }
            return bolResult;
        }

        /// <summary>
        /// 数据解析_服务器状态
        /// </summary>
        /// <param name="ipPoint"></param>
        /// <param name="strContent"></param>
        public void Analysis_serverstatus(IPEndPoint ipPoint, string strContent)
        {
            //获取服务器当前状态 
            //发送当前服务器状态
            string strCmd = ServerComm.GetCmd_ServerStatus(isCheckPort);
            byte[] connectData = Encoding.UTF8.GetBytes(strCmd);
            socketUDPServer.Socket_UDP_Send(Convert.ToString(ipPoint.Address), ipPoint.Port, connectData);
        }

        private byte[] GetValue(byte[] bytsValue, int length)
        {
            byte[] result = new byte[length];
            for (int i = 0; i < length; i++)
            {
                result[i] = bytsValue[i];
            }
            return result;
        }
        #endregion

        /// <summary>
        /// 打开各服务器
        /// </summary>
        private void OpenServers()
        {
            if (ProcessCalss.GetPidByProcessName("shike") == 0)  //如果服务器没有进程ID代表没有开启，开启服务器，下同懒得写
            {
                ProcessCalss.OpenProcedure(Profile.ShikePath);
            }
            Thread.Sleep(1000);
            if (ProcessCalss.GetPidByProcessName("AlarmServer") == 0)
            {
                ProcessCalss.OpenProcedure(Profile.AlarmServrPath);
            }
            Thread.Sleep(1000);

            if (ProcessCalss.GetPidByProcessName("VideoServer") == 0)
            {
                ProcessCalss.OpenProcedure(Profile.VideoServerPath);
            }
            Thread.Sleep(1000);

            if (ProcessCalss.GetPidByProcessName("nginx") == 0)
            {
                ProcessCalss.OpenProcedure(Profile.NginxPath);

            }

            Thread.Sleep(1000);

            tcheckServerPort = new Thread(checkServer);
            tcheckServerPort.IsBackground = true;
            tcheckServerPort.Start();
        }

        /// <summary>
        /// UDP连接错误回调
        /// </summary>
        /// <param name="ErrorInfo"></param>
        private void SocketError_UDP(string ErrorInfo)
        {
            try
            {

                radialMenu1.Symbol = strError;  //通讯异常。换个图标表示下

                if (ErrorInfo.Contains("端口异常")) //监听端口异常
                {

                    this.Invoke(gshowInfo, "本地通讯端口异常！",0);

                    return;
                }

                if (ErrorInfo.Contains("远程主机强迫关闭了一个现有的连接"))
                {
                    return;
                }


                WriteLog.DataLog(string.Format("SocketError_UDP", ErrorInfo));

            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);

            }


        }

        /// <summary>
        /// TCP连接错误回调
        /// </summary>
        /// <param name="socket_Error"></param>
        /// <param name="IPAndPort"></param>
        /// <param name="ErrorInfo"></param>
        private void SocketError_TCP(SocketService.Socket_Error socket_Error, string IPAndPort, string ErrorInfo)
        {
            try
            {
                //服务器断开
                string RecvIP = IPAndPort.Split(':')[0];
                int RecvPort = Convert.ToInt32(IPAndPort.Split(':')[1]);

                if (!isPortError)  //如果错误之前是正常的
                {
                    PortErrorDate = DateTime.Now;  //记录当前错误的时间

                    this.Invoke(gshowInfo, string.Format("本地服务器{0}端口异常！正尝试重新连接！", RecvPort),0);
                    WriteLog.DataLog(string.Format("本地服务器{0}端口异常!正尝试重新连接", RecvPort));

                }
                isPortError = true;  //端口错误置位true


                SocketTCPClient socketTCPClient;
                if (dicSocketTCPClient.TryGetValue(RecvPort, out socketTCPClient)) //查询是否在列表中
                {
                    socketTCPClient.gSocketError -= SocketError_TCP;  //删除回调
                    socketTCPClient.Socket_TCP_Close();  //以防万一，关闭一次TCP连接
                    dicSocketTCPClient.Remove(RecvPort);  //移除列表
                }
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);

            }


        }

        /// <summary>
        /// 展示信息
        /// </summary>
        /// <param name="Info">提示的内容</param>
        private void ShowInfo(string Info,long AlertId)
        {
            try
            {
                //eDesktopAlertColor color = (eDesktopAlertColor)(comboColors.SelectedItem ?? eDesktopAlertColor.Default);
                eDesktopAlertColor color = eDesktopAlertColor.Red;  //弹出框颜色（基本都是异常情况弹出所以目前固定红色）
                //eAlertPosition position = (eAlertPosition)(comboLocations.SelectedItem ?? eAlertPosition.BottomRight);
                eAlertPosition position = eAlertPosition.BottomRight;  //弹出框位置（右下角）可能被第三方软件拦截
                long _RunningAlertId = AlertId; //弹出框事件ID，用于分辨点击的是那一条事件
                DesktopAlert.Show(Info, "\uf005", eSymbolSet.Awesome, Color.Empty, color, position, DesktopAlert.AutoCloseTimeOut, _RunningAlertId, AlertClicked);
                return;
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);

            }

        }

        /// <summary>
        /// 点击弹窗框事件（没有什么事情可以处理）
        /// </summary>
        /// <param name="alertId"></param>
        private void AlertClicked(long alertId)
        {
            if (alertId == 1)
            {
                FrmNotice frmNotice = new FrmNotice();
                frmNotice.ShowDialog();
            }
            return;
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        private void SendConnect()
        {
            try
            {
                Thread.Sleep(10000);  //先停个10秒看有没有收到信息
                //开始检查端口
                if (isCheckPort)
                {
                    tcheckServerPort = new Thread(checkServer);
                    tcheckServerPort.IsBackground = true;
                    tcheckServerPort.Start();
                }
                while (true)
                {
                    if (isOpenServer) //服务器开启，发送待机命令
                    {
                        string SendData = string.Format("$Server&Standby&{0}&{1}", isCheckPort, DateTime.Now);
                        byte[] connectData = Encoding.UTF8.GetBytes(SendData);
                        socketUDPServer.Socket_UDP_Send(Profile.RemoteIP, Profile.RemotePort, connectData);
                        Thread.Sleep(6000);
                    }
                    else //发信息让伙伴开服务器
                    {
                        string SendData = string.Format("$Server&OpenServer&{0}", DateTime.Now);
                        byte[] connectData = Encoding.UTF8.GetBytes(SendData);
                        socketUDPServer.Socket_UDP_Send(Profile.RemoteIP, Profile.RemotePort, connectData);
                        Thread.Sleep(6000);
                    }
                }

            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);
                
            }

        }

        /// <summary>
        /// 检查服务器端口
        /// </summary>
        private void checkServer()
        {
            try
            {
                if (isCheckPort) //是否检查服务器端口
                {
                    SocketTCPClient Client; //TCP连接

                    if (!dicSocketTCPClient.TryGetValue(intShikePort, out Client)) //检查列表中是否有1159标识的TCP类
                    {
                        //没有则添加
                        SocketTCPClient shikeClient = new SocketTCPClient(); //TCP类
                        shikeClient.gSocketError += SocketError_TCP;  //错误回调

                        if (!shikeClient.Socket_TCP_Connection("127.0.0.1", intShikePort))  //连接本地1159TCP端口
                        {
                            return;
                        }
                        else
                        {
                            WriteLog.DataLog(string.Format("本地服务器{0}端口连接正常!", intShikePort));

                            isPortError = false;
                        }
                        dicSocketTCPClient.Add(intShikePort, shikeClient);  //添加到列表
                    }

                    if (!dicSocketTCPClient.TryGetValue(intAlarmPort, out Client)) //检查列表中是否有50000标识的TCP类
                    {
                        SocketTCPClient alarmClient = new SocketTCPClient();//TCP类
                        alarmClient.gSocketError += SocketError_TCP;//错误回调

                        if (!alarmClient.Socket_TCP_Connection("127.0.0.1", intAlarmPort))//连接本地50000TCP端口
                        {
                            return;
                        }
                        else
                        {
                            WriteLog.DataLog(string.Format("本地服务器{0}端口连接正常!", intAlarmPort));

                            isPortError = false;

                        }
                        dicSocketTCPClient.Add(intAlarmPort, alarmClient);  //添加到列表
                    }

                    if (!dicSocketTCPClient.TryGetValue(intVoidePort, out Client))  //检查列表中是否有6667标识的TCP类
                    {
                        SocketTCPClient videoClient = new SocketTCPClient(); //TCP类
                        videoClient.gSocketError += SocketError_TCP; //错误回调

                        if (!videoClient.Socket_TCP_Connection("127.0.0.1", intVoidePort))  //连接本地6667TCP端口
                        {
                            return;
                        }
                        else
                        {
                            WriteLog.DataLog(string.Format("本地服务器{0}端口连接正常!", intVoidePort));

                            isPortError = false;
                        }
                        dicSocketTCPClient.Add(intVoidePort, videoClient);  //添加到列表
                    }

                }
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);


            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if ((DateTime.Now - ConnectDate).Minutes >= 1)  //如果超过1分钟与同伴失去联系。提示一下
                {
                    if (isNotice)
                    {
                        radialMenu1.Symbol = strError;
                        //ShowInfo("与伙伴通讯超时，请检查伙伴是否正常！");
                        this.Invoke(gshowInfo, "与伙伴通讯超时，请检查伙伴是否正常！",0);

                        isNotice = false;

                        //如果与伙伴通讯超时，且本地服务器没有打开，那就直接打开本地的服务器，邮件通知伙伴异常
                        string SendData = string.Format("$Server&OpenServer&{0}", DateTime.Now);
                        byte[] connectData = Encoding.UTF8.GetBytes(SendData);
                        socketUDPServer.Socket_UDP_Send("127.0.0.1", Profile.UDPPort, connectData);

                        //if (isNoticeEmail)
                        //{
                        tNoticeEmail = new Thread(NoticeInfo);
                        tNoticeEmail.IsBackground = true;
                        tNoticeEmail.Start(string.Format("与伙伴({0})通讯超时，请检查伙伴是否正常！本地服务器打开！", Profile.RemoteIP));
                        //}

                      
                    }
                }

                //如果服务器端口没连上。
                if (isPortError)
                {
                    if ((DateTime.Now - PortErrorDate).TotalSeconds >= 30) //如果时间差大于30秒
                    {
                        
                        isCheckPort = false; //不再检查端口

                        foreach (var s in dicSocketTCPClient) //循环TCP列表
                        {
                            s.Value.Socket_TCP_Close(); //断开还连接的TCP端口
                        }
                        dicSocketTCPClient.Clear(); //清空列表

                        isOpenServer = false;
                        //干掉服务器等相关一些列有的没的进程
                        int[] ServerPids = new int[10];
                        //获取看门狗进程ID
                        ServerPids[0] = ProcessCalss.GetPidByProcessName("AlarmServerDog");
                        ServerPids[1] = ProcessCalss.GetPidByProcessName("AlmServerDog");
                        ServerPids[2] = ProcessCalss.GetPidByProcessName("SK3000Dog");
                        ServerPids[3] = ProcessCalss.GetPidByProcessName("VideoDog");
                        //获取服务器进程ID
                        ServerPids[4] = ProcessCalss.GetPidByProcessName("shike");
                        ServerPids[5] = ProcessCalss.GetPidByProcessName("AlarmServer");
                        ServerPids[6] = ProcessCalss.GetPidByProcessName("VideoServer");
                        //获取我也不知道是什么程序的进程ID
                        ServerPids[7] = ProcessCalss.GetPidByProcessName("nginx");
                        ServerPids[8] = ProcessCalss.GetPidByProcessName("hfs");
                        ServerPids[9] = ProcessCalss.GetPidByProcessName("NetPanelProc");


                        for (int i = 0; i < ServerPids.Length; i++)
                        {
                            if (ServerPids[i] != 0) //如果进程ID不等于0（等于0是没获取到ID）
                            {
                                ProcessCalss.CloseProcedure(ServerPids[i]); //干掉进程

                            }
                        }

                        if (isNoticeEmail)
                        {
                            tNoticeEmail = new Thread(NoticeInfo);
                            tNoticeEmail.IsBackground = true;
                            tNoticeEmail.Start(string.Format("本地服务器端口连接异常，通知伙伴服务({0})打开服务器", Profile.RemoteIP));
                            ConnectDate = DateTime.Now;
                            isNotice = true;
                        }

                        WriteLog.DataLog(string.Format("本地服务器端口连接异常,关闭本地各服务器,通知伙伴服务({0})打开服务器", Profile.RemoteIP));

                    }
                    else
                    {

                        tcheckServerPort = new Thread(checkServer);
                        tcheckServerPort.IsBackground = true;
                        tcheckServerPort.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);

            }

        }

        private void timReset_Tick(object sender, EventArgs e)
        {
            isNoticeEmail = true;
            isNotice = true;
        }


        #region 窗体移动

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;




        private void FrmMain_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }
        #endregion


        #region 窗口置顶

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);


        #endregion


        #region 窗体最小化
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void FrmMain_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
            }
        }
        #endregion


    }
}
